package com.unicomcz.login;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.unicomcz.ActionBase;
import com.unicomcz.commision.CommType;
import com.unicomcz.query.AlertType;

public class LoginAction extends ActionBase
{
    //private UserInfo userInfo;
    public UserInfo getUserInfo()
    {
        return userInfo;
    }
    public void setUserInfo(UserInfo userInfo)
    {
        this.userInfo = userInfo;
    }
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        log = Logger.getLogger(this.getClass());
        String volidateCode = (String)session.getAttribute("VALIDATE_KEY");
        log.debug(userInfo.getUserId()+"试图登陆系统!");
        boolean dbFlag = setupConn("dls");
        if (!dbFlag) {
            log.debug(userInfo.getUserId()+"登陆系统失败!因为建立数据库连接失败");
            return INPUT;
        }
        userInfo.setUserId(userInfo.getUserId().toUpperCase());
        String sql = "select passwd,depart_name,mobile,email,user_level,jf_task,qx,depart_id,depart_code,depart_name";
        sql += " from dls_code_dls ";
        sql += " where upper(user_id)=?";
        String[] userInfoRow = getSingle(sql);
        if ((volidateCode==null)||(volidateCode.compareTo(userInfo.getVerifyCode())!=0)) {
            //验证码错误
            addActionMessage("验证码错误！");
            return INPUT;
        }
        if (userInfoRow == null) {
            //找不到用户
            addActionMessage("用户不存在！");
            return INPUT;
        }
        if (userInfoRow[0].compareTo(userInfo.getPassword())!=0) {
            //密码不对
            addActionMessage("密码错误！");
            return INPUT;
        }
        userInfo.setUserName(userInfoRow[1]);
        userInfo.setMobile(userInfoRow[2]);
        userInfo.setEmail(userInfoRow[3]);
        userInfo.setUserLevel(userInfoRow[4]);
        userInfo.setJfTask(userInfoRow[5]);
        userInfo.setLogin(true);
        userInfo.setQx(userInfoRow[6]);
        userInfo.setDepartId(userInfoRow[7]);
        userInfo.setDepartCode(userInfoRow[8]);
        userInfo.setDeptName(userInfoRow[9]);
        session.setAttribute("USER_INFO", userInfo);
        execProc("{call login_log(?,?)}");
        loadCommType("2G");
        loadCommType("3G");
        loadCommType("GW");
        loadAlertType();
        loadAllDepart();
        loadPriv();
        tearDown();
        return SUCCESS;
    }
   protected void regProcParam() {
       try {
           cstmt.setString(1, userInfo.getUserId().toUpperCase());
           cstmt.setString(2,ServletActionContext.getRequest().getRemoteAddr());
       }catch(Exception e) {
           
       }
    }

    protected void regParam2single() {
        try {
            pstmt.setString(1, userInfo.getUserId().toUpperCase());
        }catch(Exception e) {
            
        }
    }
    public void validate(){
        if (userInfo.getVerifyCode().length()==0) {
            addFieldError("userInfo.verifyCode","验证码不能为空！");
            addActionMessage("验证码不能为空！");
        }
        if (userInfo.getUserId().length()==0) {
            addFieldError("userInfo.verifyCode","用户名不能为空！");
            addActionMessage("用户名不能为空！");
        }
        if (userInfo.getPassword().length()==0) {
            addFieldError("userInfo.verifyCode","密码不能为空！");
            addActionMessage("密码不能为空！");
        }
    }
    protected void loadPriv(){
    	String sqlStr = "select b.menu_id,b.menu_name,b.menu_action,b.menu_group "
                      +"from dls_code_dls a,dls_code_menu b,dls_menu_priv c "
                      +"where a.user_level=c.user_level and b.menu_id=c.menu_id and b.show_tag=0 and a.user_id=? "
                      +"order by b.group_order,list_order" ;
    	ResultSet rs = null;
    	List priv = new ArrayList();
    	List a = new ArrayList();
    	try {
            pstmt = conn.prepareStatement(sqlStr);
            pstmt.setString(1, userInfo.getUserId());
            rs = pstmt.executeQuery(); 
            
            while (rs.next()) {
            	Menu m = new Menu();
                m.setMenuId(rs.getString(1));
                m.setMenuName(rs.getString(2));
                m.setMenuAction(rs.getString(3));
                m.setMenuGroup(rs.getString(4));
            	List menus;
            	int idx;
                if (!a.contains(rs.getString(4))){
                	menus = new ArrayList();
                	menus.add(m);
                	idx = a.size();
                	a.add(rs.getString(4));
                	priv.add(menus);
                }else{
                	menus = (ArrayList)priv.get(a.indexOf(rs.getString(4)));
                	menus.add(m);
                	idx = a.indexOf(rs.getString(4));
                	priv.set(idx, menus);
                }
            }
            
         }catch(Exception e) {
             log.debug(e);
         }
         try {
             rs.close();
         }catch(Exception e) {
             
         }
         try {
             pstmt.close();
         }catch(Exception e) {
             
         }
         userInfo.setPriv(priv);
         String[] privName = new String[a.size()];
         for (int i=0;i<a.size();i++){
        	 privName[i]=(String)a.get(i);
         }
         userInfo.setPrivName(privName);
    }
    protected void loadCommType(String commType) {
        ResultSet rs = null;
        String[] rtv = null;
        List types = new ArrayList<CommType>();
        try {
           pstmt = conn.prepareStatement("SELECT comm_id,comm_name,brand,comm_alias,comm_Remarks,comm_action FROM dls_code_comm WHERE brand=? and list_id>0 order by list_id");
           pstmt.setString(1, commType);
           rs = pstmt.executeQuery();  
           while (rs.next()) {
               CommType ct = new CommType();
               ct.setCommId(rs.getString(1));
               ct.setCommName(rs.getString(2));
               ct.setBrand(rs.getString(3));
               ct.setCommAlias(rs.getString(4));
               ct.setCommRemarks(rs.getString(5));
               ct.setCommAction(rs.getString(6));
               types.add( ct);
           }
           
        }catch(Exception e) {
            log.debug(e);
        }
        try {
            rs.close();
        }catch(Exception e) {
            
        }
        try {
            pstmt.close();
        }catch(Exception e) {
            
        }
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        session.setAttribute("COMM_"+commType, types);
    }
    protected void loadAlertType() {
        ResultSet rs = null;
        String[] rtv = null;
        List types = new ArrayList<AlertType>();
        try {
           pstmt = conn.prepareStatement("SELECT alert_id,alert_name,brand,alert_alias,alert_Remarks,alert_action FROM dls_code_ALERT  order by list_id");
           rs = pstmt.executeQuery();  
           while (rs.next()) {
               AlertType ct = new AlertType();
               ct.setAlertId(rs.getString(1));
               ct.setAlertName(rs.getString(2));
               ct.setBrand(rs.getString(3));
               ct.setAlertAlias(rs.getString(4));
               ct.setAlertRemarks(rs.getString(5));
               ct.setAlertAction(rs.getString(6));
               types.add( ct);
           }
           
        }catch(Exception e) {
            log.debug(e);
        }
        try {
            rs.close();
        }catch(Exception e) {
            
        }
        try {
            pstmt.close();
        }catch(Exception e) {
            
        }
        
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        session.setAttribute("ALERT", types);
        
    }
    
    protected void loadAllDepart() {
        String sqlStr = "select b.depart_code,b.depart_name,b.depart_id,b.qx from dls_user_dls a,dls_code_dls b " + 
        		" where a.depart_code=b.depart_code and a.user_id=?";
        ResultSet rs = null;
        String[] rtv = null;
        List types = new ArrayList<DepartInfo>();
        try {
           pstmt = conn.prepareStatement(sqlStr);
           pstmt.setString(1, userInfo.getUserId());
           rs = pstmt.executeQuery();  
           while (rs.next()) {
               DepartInfo dp = new DepartInfo();
               dp.setDepartCode(rs.getString(1));
               dp.setDepartName(rs.getString(2));
               dp.setDepartId(rs.getString(3));
               dp.setQx(rs.getString(4));
               types.add(dp);
           }
           
        }catch(Exception e) {
            log.debug(e);
        }
        try {
            rs.close();
        }catch(Exception e) {
            
        }
        try {
            pstmt.close();
        }catch(Exception e) {
            
        }
       // if (types.size()>1) {
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpSession session = request.getSession();
            session.setAttribute("ALLDEPT", types);
       // }
    }
}
